<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="服务项目" prop="serviceName">
        <el-input
          v-model="queryParams.serviceName"
          placeholder="请输入服务项目"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="服务分类" prop="categoryId">
        <el-select style="width: 200px" v-model="queryParams.categoryId" placeholder="请选择服务分类" clearable>
          <el-option
            v-for="dict in service_category"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="商家名称" prop="store.storeName">
        <el-input
            v-model="queryParams.store.storeName"
            placeholder="请输入商家名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['serviceManagement:serviceManagement:add']"
        >发布服务</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['serviceManagement:serviceManagement:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['serviceManagement:serviceManagement:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['serviceManagement:serviceManagement:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="serviceManagementList" @selection-change="handleSelectionChange">
      <el-table-column min-width="100" type="selection" width="55" align="center" />
      <el-table-column min-width="100" label="服务编号" align="center" prop="serviceId" />
      <el-table-column min-width="200" label="服务项目" align="center" prop="serviceName" />
      <el-table-column min-width="200" label="商家名称" align="center" prop="store.storeName" />
      <el-table-column min-width="100" label="服务分类" align="center" prop="categoryId">
        <template #default="scope">
          <dict-tag :options="service_category" :value="scope.row.categoryId"/>
        </template>
      </el-table-column>
      <el-table-column min-width="100" label="原价（元）" align="center" prop="originalPrice" />
      <el-table-column min-width="100" label="现价（元）" align="center" prop="currentPrice" />
      <el-table-column min-width="200" label="服务介绍" align="center" prop="serviceDesc" />
      <el-table-column min-width="100" label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="200" label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['serviceManagement:serviceManagement:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['serviceManagement:serviceManagement:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改服务管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="serviceManagementRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="服务项目" prop="serviceName">
          <el-input v-model="form.serviceName" placeholder="请输入服务项目" />
        </el-form-item>
        <el-form-item label="原价（元）" prop="originalPrice">
          <el-input v-model="form.originalPrice" placeholder="请输入原价" />
        </el-form-item>
        <el-form-item label="现价（元）" prop="currentPrice">
          <el-input v-model="form.currentPrice" placeholder="请输入现价" />
        </el-form-item>
        <el-form-item label="服务介绍" prop="serviceDesc">
          <el-input v-model="form.serviceDesc" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="服务分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择服务分类">
            <el-option
              v-for="dict in service_category"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="门店" prop="storeId">
          <el-select v-model="form.storeId" placeholder="请选择门店">
            <el-option
                v-for="store in merchantRankingList"
                :key="store.storeId"
                :label="store.storeName"
                :value="store.storeId"/>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ServiceManagement">
import { listServiceManagement, getServiceManagement, delServiceManagement, addServiceManagement, updateServiceManagement } from "@/api/serviceManagement/serviceManagement";
import {listMerchantRanking} from "@/api/merchantManagement/merchantRanking";

const { proxy } = getCurrentInstance();
const { service_category } = proxy.useDict('service_category');

const serviceManagementList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const merchantRankingList = ref([]); // 新增门店列表

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    serviceName: null,
    categoryId: null,
    store: {
      storeName: null
    }
  },
  rules: {
    serviceName: [
      { required: true, message: "服务项目不能为空", trigger: "blur" }
    ],
    originalPrice: [
      { required: true, message: "原价不能为空", trigger: "blur" }
    ],
    currentPrice: [
      { required: true, message: "现价不能为空", trigger: "blur" }
    ],
    serviceDesc: [
      { required: true, message: "服务介绍不能为空", trigger: "blur" }
    ],
    categoryId: [
      { required: true, message: "服务分类不能为空", trigger: "change" }
    ],
    storeId: [
      { required: true, message: "门店不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询服务管理列表 */
function getList() {
  loading.value = true;
  listServiceManagement(queryParams.value).then(response => {
    console.log(queryParams.value);
    serviceManagementList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    serviceId: null,
    serviceName: null,
    originalPrice: null,
    currentPrice: null,
    serviceDesc: null,
    createTime: null,
    categoryId: null,
    storeId: null,
    ext1: null,
    ext2: null,
    ext3: null,
    ext4: null,
    ext5: null,
    store: {
      storeName: null
    }
  };
  proxy.resetForm("serviceManagementRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.serviceId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  getStoreNameList(); // 获取所有门店
  open.value = true;
  title.value = "添加服务管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _serviceId = row.serviceId || ids.value
  getServiceManagement(_serviceId).then(response => {
    form.value = response.data;
    getStoreNameList(); // 获取所有门店
    open.value = true;
    title.value = "修改服务管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["serviceManagementRef"].validate(valid => {
    if (valid) {
      if (form.value.serviceId != null) {
        updateServiceManagement(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addServiceManagement(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _serviceIds = row.serviceId || ids.value;
  proxy.$modal.confirm('是否确认删除服务管理编号为"' + _serviceIds + '"的数据项？').then(function() {
    return delServiceManagement(_serviceIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('serviceManagement/serviceManagement/export', {
    ...queryParams.value
  }, `serviceManagement_${new Date().getTime()}.xlsx`)
}

/** 查询商户排名列表 */
function getStoreNameList() {
  loading.value = true;
  listMerchantRanking(queryParams.value).then(response => {
    merchantRankingList.value = response.rows;
    console.log(merchantRankingList.value);
    total.value = response.total;
    loading.value = false;
  });
}

getList();
getStoreNameList()
</script>
